<template>
  <div>
    <!-- head -->
    <el-affix :offset="94">
      <div class="card affix-container pt15 pb14">
        <el-page-header @back="router.go(-1)">
          <template #content>
            <span class="fsize16">{{ isEdit ? "编辑菜品" : "新增菜品" }}</span>
          </template>
          <template #extra>
            <div class="foot">
              <el-button @click="router.go(-1)">取消</el-button>
              <el-button @click="onSubmit" type="primary">保存</el-button>
            </div>
          </template>
        </el-page-header>
      </div>
    </el-affix>
    <!-- head end -->
    <div class="card mt10">
      <el-form :model="goodsForm" label-width="120px" :rules="rules" ref="ruleFormRef">
        <!-- 基础信息 -->
        <div>
          <h4 id="section1" class="fsize16">基础信息</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="菜品名称" prop="name">
                <el-input
                  v-model="goodsForm.name"
                  placeholder="请输入菜品名称"
                  clearable
                  :disabled="!goodsForm.isModify"
                ></el-input>
              </el-form-item>
              <el-form-item label="数字助记码" prop="helpCode">
                <el-input
                  v-model="goodsForm.detail.helpCode"
                  placeholder="请输入数字助记码"
                  clearable
                  :disabled="!goodsForm.isModify"
                ></el-input>
              </el-form-item>
              <el-form-item label="菜品分类" prop="foodTypeId">
                <el-tree-select
                  class="width320"
                  v-model="goodsForm.foodTypeId"
                  :data="foodType"
                  :render-after-expand="false"
                  check-strictly
                  :disabled="!goodsForm.isModify"
                />
                <el-text class="ml10 pointer" type="danger" @click.stop="openCategoryDialog('新增', { appletShow: 1 })">
                  <el-icon>
                    <Plus />
                  </el-icon>
                  新增分类
                </el-text>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="菜品别名" prop="byName">
                <el-input
                  v-model="goodsForm.byName"
                  placeholder="请输入菜品别名"
                  clearable
                  :disabled="!goodsForm.isModify"
                ></el-input>
              </el-form-item>
              <el-form-item label="拼音助记码" prop="pinYin">
                <el-input v-model="goodsForm.detail.pinYin" placeholder="自动生成" clearable disabled></el-input>
              </el-form-item>
              <el-form-item label="菜品类型" prop="type">
                <el-radio-group v-model="goodsForm.type" :disabled="isEdit">
                  <el-radio :label="1">普通菜</el-radio>
                  <el-radio :label="2">套菜</el-radio>
                  <el-radio :label="3">线下临时菜</el-radio>
                  <el-radio :label="4">打包盒</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <!-- 是否是原料start -->
            <el-col :span="24">
              <el-form-item label="是否原料" prop="type">
                <el-radio-group v-model="goodsForm.detail.isGoods">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>

              <div v-if="goodsForm.detail.isGoods" style="width: 50%">
                <el-form-item label="原料类别" prop="detail.goodsCategoryId">
                  <div class="flx-default w100">
                    <el-tree-select
                      class="w100"
                      node-key="value"
                      v-model="goodsForm.detail.goodsCategoryId"
                      :data="waresCategory"
                      :render-after-expand="false"
                      check-strictly
                    />
                  </div>
                </el-form-item>
              </div>
            </el-col>
            <!-- 是否是原料end -->
          </el-row>
        </div>

        <!-- 基础信息 end-->
        <!-- 菜品构成 -->
        <div>
          <h4 id="section2" class="fsize16">菜品构成</h4>
          <!-- 菜品规格 -->
          <el-form-item label="菜品规格" prop="spec">
            <div class="spec-table">
              <el-table :data="goodsForm.speclist">
                <el-table-column prop="specName" label="是否默认">
                  <template #default="scope">
                    <div class="flx-align-center">
                      <el-button class="ml10" type="primary" v-if="scope.row.isDefault" :disabled="!goodsForm.isModify">
                        默认
                      </el-button>
                      <el-button class="ml10" v-else @click="setSpecDefault(scope.$index)" :disabled="!goodsForm.isModify">
                        设为默认
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="specName" label="规格名称">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.specName"
                      placeholder="请输入"
                      controls-position="right"
                      style="width: 100%"
                      :disabled="!goodsForm.isModify"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="posPrice" label="销售价">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.posPrice"
                      oninput="value=value.replace(/[^0-9.]/g,'')"
                      placeholder="请输入"
                      :disabled="false"
                    >
                      <template #append>
                        <div>元</div>
                      </template>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="vipPrice" label="会员价">
                  <template #default="scope">
                    <el-input v-model="scope.row.vipPrice" oninput="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入">
                      <template #append>
                        <div>元</div>
                      </template>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="purPrice" label="预估成本">
                  <template #default="scope">
                    <el-input v-model="scope.row.purPrice" oninput="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入">
                      <template #append>
                        <div>元</div>
                      </template>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="code" label="条形码">
                  <template #default="scope">
                    <el-input v-model="scope.row.code" placeholder="请输入" :disabled="!goodsForm.isModify" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="74">
                  <template #default="scope">
                    <el-button
                      v-if="!scope.row.isDefault"
                      :disabled="!goodsForm.isModify"
                      type="danger"
                      @click="deleteSpecRow(scope.$index, -1)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <el-button
              class="mt10"
              type="danger"
              v-if="goodsForm.type !== 2"
              @click="onAddSpecItem"
              :disabled="!goodsForm.isModify"
            >
              添加多个规格
            </el-button>
          </el-form-item>
          <!-- 菜品规格 end -->
          <!-- 套菜 -->
          <div v-if="goodsForm.type === 2">
            <el-form-item label="套餐明细">
              <div style="width: 100%">
                <div class="flx-justify-between">
                  <div class="fsize12 text-describe-color">
                    套餐明细统计金额是按比例均摊套餐价格：单明细统计金额=(单明细执行单价/已点明细执行单价总和)*套餐实时价格
                  </div>
                  <el-button :icon="Plus" @click="addPackGrou" :disabled="!goodsForm.isModify">自定义分组</el-button>
                </div>
                <div class="package mt10" v-for="(pack, packIx) in goodsForm.packlist" :key="packIx">
                  <el-card>
                    <template #header>
                      <div class="flx-justify-between">
                        <div class="flx-default">
                          <div>
                            <el-input
                              v-model="pack.name"
                              placeholder="请输入分组名称"
                              style="width: 160px"
                              :disabled="!goodsForm.isModify"
                            />
                          </div>
                          <div class="ml10">
                            <el-select v-model="pack.selectType" style="width: 100px" :disabled="!goodsForm.isModify">
                              <el-option v-for="item in collocation" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                          </div>
                          <div class="ml10 fsize12 text-assist-color">
                            <div class="flx-center" v-if="pack.selectType === 1">
                              <el-input
                                version
                                v-model="pack.quantityStar"
                                oninput="value=value.replace(/[^0-9.]/g,'')"
                                style="width: 60px"
                                :disabled="!goodsForm.isModify"
                              />
                              <span class="ml10 mr10">~</span>
                              <el-input
                                v-model="pack.quantityEnd"
                                oninput="value=value.replace(/[^0-9.]/g,'')"
                                style="width: 60px"
                                :disabled="!goodsForm.isModify"
                              />
                              <div class="ml20">
                                <el-checkbox v-model="pack.isSelectSame" label="" :disabled="!goodsForm.isModify" />
                                <span class="ml10">可选相同菜品</span>
                              </div>
                            </div>
                            <span v-if="pack.selectType === 3">
                              明细数量和种类任 选，用法：不限量免费菜品/加价填写后随点菜数加价
                            </span>
                            <span v-if="pack.selectType === 2">共有{{ pack.packdetails.length }}种菜</span>
                          </div>
                        </div>
                        <div class="pointer">
                          <el-button type="primary" @click="openSelectTable('菜品选择', packIx)" :disabled="!goodsForm.isModify">
                            <el-icon><Plus /></el-icon>
                            添加菜品
                          </el-button>
                          <el-button type="danger" @click="delPackage(packIx)" :disabled="!goodsForm.isModify">
                            <el-icon><Delete /></el-icon>
                            删除分组
                          </el-button>
                        </div>
                      </div>
                    </template>
                    <div>
                      <el-table :data="pack.packdetails" border>
                        <el-table-column type="selection" width="55" v-if="pack.selectType === 1 || pack.selectType === 3" />
                        <el-table-column prop="foodName" label="菜品名称" />
                        <el-table-column prop="specName" label="规格" />
                        <el-table-column prop="quantity" label="数量">
                          <template #default="scope">
                            <el-input v-model="scope.row.quantity" oninput="value=value.replace(/[^0-9.]/g,'')" />
                          </template>
                        </el-table-column>
                        <el-table-column prop="setPrice" label="套餐执行单价	">
                          <template #default="scope">
                            <el-input v-model="scope.row.setPrice" oninput="value=value.replace(/[^0-9.]/g,'')" />
                          </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center">
                          <template #default="scope">
                            <el-button type="danger" @click="deleteSpecRow(scope.$index, packIx)" :disabled="!goodsForm.isModify">
                              删除
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                  </el-card>
                  <div class="slotBtn">
                    <el-button :disabled="packIx === 0" type="primary" :icon="Top" @click="moveUp(packIx)" />
                    <el-button
                      :disabled="packIx === goodsForm.packlist.length - 1"
                      type="primary"
                      :icon="Bottom"
                      @click="moveDown(packIx)"
                    />
                  </div>
                </div>
              </div>
            </el-form-item>
          </div>
          <!-- 套菜 end -->
          <!-- 普通菜 -->
          <div v-else>
            <!-- 菜品做法 -->
            <el-form-item label="做法">
              <div class="add-table-box" v-if="goodsForm.tasklist.length > 0">
                <el-table border :data="goodsForm.tasklist">
                  <el-table-column type="index" label="序号" width="68"></el-table-column>
                  <el-table-column prop="taskName" label="做法名称"></el-table-column>
                  <el-table-column prop="taskPrice" label="变价金额">
                    <template #default="scope">
                      <span>{{ scope.row.taskPrice === 0 ? "免费" : scope.row.taskPrice }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="selectType" label="是否必选">
                    <template #default="scope">
                      <el-switch
                        v-model="scope.row.selectType"
                        :active-value="1"
                        :inactive-value="0"
                        @change="event => onSelectType(event, scope.$index)"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="isDefault" label="默认推荐">
                    <template #default="scope">
                      <el-checkbox v-model="scope.row.isDefault" :disabled="scope.row.selectType === 1" />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作">
                    <template #default="scope">
                      <el-button type="danger" @click="deleteTaskRow(scope.$index, 'tasklist')" :disabled="!goodsForm.isModify">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div>
                <el-button type="primary" @click="openSelectTable('做法选择')" :disabled="!goodsForm.isModify">
                  添加做法
                </el-button>
              </div>
            </el-form-item>
            <!-- 菜品做法 end -->
            <!-- 菜品加料 -->
            <el-form-item label="加料">
              <div class="add-table-box" v-if="goodsForm.feedlist.length > 0">
                <el-table border :data="goodsForm.feedlist">
                  <el-table-column type="index" label="序号" width="68"></el-table-column>
                  <el-table-column prop="feedName" label="做法名称"></el-table-column>
                  <el-table-column prop="feedPrice" label="变价金额">
                    <template #default="scope">
                      <span>{{ scope.row.feedPrice === 0 ? "免费" : scope.row.feedPrice }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="isDefault" label="默认推荐">
                    <template #default="scope">
                      <el-checkbox v-model="scope.row.isDefault" />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作">
                    <template #default="scope">
                      <el-button type="danger" @click="deleteTaskRow(scope.$index, 'feedlist')" :disabled="!goodsForm.isModify">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div>
                <el-button type="primary" @click="openSelectTable('加料选择')" :disabled="!goodsForm.isModify">
                  添加加料
                </el-button>
              </div>
            </el-form-item>
            <!-- 菜品加料 end -->
          </div>
          <!-- 普通菜 end -->
        </div>
        <!-- 菜品构成 end -->
        <!-- 其他信息 -->
        <div>
          <h4 id="section4" class="fsize16">其他信息</h4>
          <el-row>
            <el-col :span="10">
              <el-form-item label="支持业务" prop="businessObject">
                <el-checkbox-group v-model="goodsForm.businessObject" :disabled="!goodsForm.isModify">
                  <el-checkbox :label="1">堂食</el-checkbox>
                  <el-checkbox :label="2">外卖</el-checkbox>
                  <el-checkbox :label="3">自提</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="称重菜" prop="weighType">
                <el-radio-group v-model="goodsForm.detail.weighType" :disabled="!goodsForm.isModify">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="菜品状态" prop="sellStatus">
                <el-radio-group v-model="goodsForm.sellStatus" :disabled="!goodsForm.isModify">
                  <el-radio :label="im.value" v-for="im in sales" :key="im.value">{{ im.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="微点餐状态" prop="mallStatus">
                <el-radio-group v-model="goodsForm.mallStatus" :disabled="!goodsForm.isModify">
                  <el-radio :label="item.value" v-for="item in mall" :key="item.value">{{ item.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="收银端临时改价" prop="isChangePrice">
                <el-radio-group v-model="goodsForm.detail.isChangePrice" :disabled="!goodsForm.isModify">
                  <el-radio :label="true">允许</el-radio>
                  <el-radio :label="false">不允许</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="收银端手动打折" prop="isDiscount">
                <el-radio-group v-model="goodsForm.detail.isDiscount" :disabled="!goodsForm.isModify">
                  <el-radio :label="true">允许</el-radio>
                  <el-radio :label="false">不允许</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="出品部门" prop="departType">
                <el-radio-group v-model="goodsForm.detail.departType" :disabled="!goodsForm.isModify">
                  <el-radio :label="0">与菜品分类一致</el-radio>
                  <el-radio :label="1">自定义出品部门</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="设置出品部门" prop="detail.departId" v-if="goodsForm.detail.departType === 1">
                <el-select
                  v-model="goodsForm.detail.departId"
                  placeholder="请选择"
                  style="width: 100%"
                  :disabled="!goodsForm.isModify"
                >
                  <el-option
                    v-for="category in departmentList"
                    :key="category.name"
                    :label="category.name"
                    :value="category.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="保质期" prop="warrantyValue">
                <el-input class="w100" v-model="goodsForm.detail.warrantyValue" :controls="false" :disabled="!goodsForm.isModify">
                  <template #append>
                    <el-select v-model="goodsForm.detail.warrantyType" style="width: 78px">
                      <el-option v-for="unit in timeUnit" :label="unit.label" :value="unit.value" :key="unit.label" />
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="组织机构" prop="organizationId">
                <el-select
                  v-model="goodsForm.organizationId"
                  placeholder="请选择"
                  style="width: 100%"
                  :disabled="!goodsForm.isModify"
                >
                  <el-option v-for="category in organization" :key="category.name" :label="category.name" :value="category.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="菜品起售份数" prop="upSell">
                <el-input-number
                  class="w100"
                  v-model="goodsForm.detail.upSell"
                  :controls="false"
                  :disabled="!goodsForm.isModify"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="增量售卖数" prop="addSell">
                <el-input-number
                  class="w100"
                  v-model="goodsForm.detail.addSell"
                  :disabled="!goodsForm.isModify"
                  :controls="false"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="最低折扣" prop="minDiscount">
                <el-input-number
                  class="w100"
                  v-model="goodsForm.detail.minDiscount"
                  :disabled="!goodsForm.isModify"
                  :controls="false"
                />
                <div class="text-describe-color">说明: 90表示9折, 即90%</div>
              </el-form-item>
              <el-form-item label="会员积分" prop="pointValue">
                <el-input type="number" :min="0" v-model.number="goodsForm.detail.pointValue">
                  <template #append>
                    <el-select v-model="goodsForm.detail.pointType" style="width: 150px">
                      <el-option label="分(固定积分)" :value="1" />
                      <el-option label="%(销售额百分比)" :value="2" />
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="排序" prop="sort">
                <el-input-number class="w100" v-model="goodsForm.detail.sort" :disabled="!goodsForm.isModify" :controls="false" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 其他信息 end -->
        <!-- 手机端展示 -->
        <div>
          <h4 id="section6" class="fsize16">手机端展示</h4>
          <el-form-item label="菜品图片" prop="image">
            <UploadImg v-model:image-url="goodsForm.detail.image" :file-size="3" :disabled="!goodsForm.isModify">
              <template #empty>
                <el-icon><Picture /></el-icon>
              </template>
              <template #tip> 图片大小不能超过 3M </template>
            </UploadImg>
          </el-form-item>
          <!-- <el-row>
            <el-col :span="10">
              <el-form-item label="手机点餐端展示" prop="isShow">
                <el-radio-group v-model="goodsForm.detail.isShow" :disabled="!goodsForm.isModify">
                  <el-radio :label="true">否</el-radio>
                  <el-radio :label="false">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row> -->
          <el-row>
            <el-col :span="10">
              <el-form-item label="菜品描述" prop="remark">
                <el-input
                  v-model="goodsForm.detail.remark"
                  placeholder="最多50字,在手机点餐端展示"
                  clearable
                  :disabled="!goodsForm.isModify"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="菜品详细描述" prop="remarkDetail">
                <el-input
                  v-model="goodsForm.detail.remarkDetail"
                  placeholder="最多200字,在手机点餐端菜品详情页展示"
                  type="textarea"
                  :disabled="!goodsForm.isModify"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 手机端展示 end -->
      </el-form>
    </div>
    <SelectTable @selected-list="handleSelectedList" ref="selectTableRef" />
    <CategoryDialog ref="categoryDialogRef" />
  </div>
</template>

<script setup lang="ts" name="GoodsAdd">
import { ref, reactive, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import UploadImg from "@/components/Upload/Img.vue";
import SelectTable from "@/components/SelectTreeData/index.vue";
import CategoryDialog from "@/views/goods/components/CategoryDialog.vue";
import { addFoodCategory } from "@/api/modules/goods";
import { getWaresCategoryList } from "@/api/modules/inventory"; // 原料类别
import {
  getFoodtaskList,
  getFoodtaskCategory,
  getFoodFeedCategory,
  getFoodFeedList,
  createFood,
  editFood,
  getFoodDedail,
  getFoodCategoryList,
  getGoodsSingleItem
} from "@/api/modules/goods";
import { useSelectStore } from "@/stores/modules/dict";
import { Delete, Plus, Bottom, Top } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";
import { getOrganizationList } from "@/api/modules/operation";
import { replaceArrayItems, transformCategories } from "@/utils";
import { Goods } from "@/api/interface";
import { getDepartMentList } from "@/api/modules/operation";

const router = useRouter();
const route = useRoute();

const goodsForm = reactive<any>({
  id: 0,
  corpId: 0,
  storeId: 0,
  isModify: true,
  foodTypeId: null,
  type: 1,
  number: "123",
  name: "",
  byName: "",
  businessType: "",
  mallStatus: 1,
  sellStatus: 1,
  specFlag: true,
  foodSpecId: 0,
  isDelete: true,
  organizationId: 0,
  statusText: "",
  foodCategoryName: "",
  foodTypeName: "",
  foodSpecName: "",
  businessObject: [1, 2, 3],
  detail: {
    isGoods: 0, //是否是原料分类
    goodsCategoryId: "", // 原料分类id
    foodId: 0,
    corpId: 0,
    storeId: 0,
    isHeft: true,
    helpCode: "",
    pinYin: "",
    warrantyValue: 1,
    warrantyType: 0,
    isPrint: true,
    gearOpening: "",
    isChangePrice: true,
    isDiscount: true,
    minDiscount: 0,
    weighType: 0,
    upSell: 0,
    departType: 1,
    addSell: 0,
    division: "",
    image: "",
    isShow: true,
    subscript: "",
    remark: "",
    remarkDetail: "",
    pointValue: 0,
    pointType: 1
  },
  speclist: [
    {
      id: 0,
      corpId: 0,
      storeId: 0,
      foodId: 0,
      code: "",
      specName: "标准",
      onLine: true,
      isShare: true,
      isDelete: true,
      foodShopPriceId: 0,
      isDefault: true,
      posPrice: 0,
      vipPrice: 0,
      purPrice: 0,
      rmoPrice: 0,
      isSelected: true,
      isExclusive: true,
      name: "",
      price: 0
    }
  ],
  tasklist: [],
  feedlist: [],
  packlist: [
    {
      id: 0,
      foodId: 0,
      corpId: 0,
      storeId: 0,
      name: "",
      selectType: 2,
      plateType: 0,
      quantityStar: 1,
      quantityEnd: 1,
      isSelectSame: false,
      isDelete: true,
      packdetails: []
    }
  ]
});

const foodType = ref<any>([]);
const timeUnit = ref<any>([]);
const organization = ref<any>([]);
const ruleFormRef = ref<FormInstance>();
const isEdit = ref(false);
const collocation = ref<any>([]);
const sales = ref<any>([]);
const mall = ref<any>([]);

const rules = reactive({
  name: [{ required: true, message: "请填写菜品名称" }],
  foodTypeId: [{ required: true, message: "请选择菜品分类" }],
  detail: {
    departId: [{ required: true, message: "请选择出品部门" }],
    goodsCategoryId: [
      {
        validator: (rule, value, callback) => {
          if (goodsForm.detail.isGoods && goodsForm.detail.goodsCategoryId === "") {
            callback(new Error("请选择一项菜品"));
          } else {
            callback();
          }
        }
      }
    ]
  },
  businessObject: [{ required: true, message: "支持业务必选" }]
});

const setSpecDefault = (ix: number) => {
  goodsForm.speclist = goodsForm.speclist.map(spec => {
    spec.isDefault = false;
    return spec;
  });
  goodsForm.speclist[ix].isDefault = true;
};

const onSelectType = (val: number, index: number) => {
  if (val === 1) {
    goodsForm.tasklist[index].isDefault = true;
  }
};

const deleteSpecRow = (index: number, pix: number) => {
  if (pix === -1) {
    goodsForm.speclist.splice(index, 1);
  } else {
    goodsForm.packlist[pix].packdetails.splice(index, 1);
  }
};

const delPackage = (index: number) => {
  if (goodsForm.packlist.length > 1) {
    goodsForm.packlist.splice(index, 1);
  }
};

const selectTableRef = ref<InstanceType<typeof SelectTable> | null>(null);
const openSelectTable = (title: string, ix?: number) => {
  const params = {
    title,
    isView: false,
    index: ix,
    selTags:
      title === "做法选择"
        ? goodsForm.tasklist.map(i => {
            return { id: i.taskId, name: i.taskName };
          })
        : title === "加料选择"
        ? goodsForm.feedlist.map(i => {
            return { id: i.feedId, name: i.feedName };
          })
        : title === "菜品选择"
        ? goodsForm.packlist[ix].packdetails.map(i => {
            return { id: i.foodId, name: i.foodName };
          })
        : [],
    columns:
      title === "做法选择"
        ? [
            { type: "selection", width: 80 },
            { prop: "name", label: "做法名称", align: "left" },
            { prop: "price", label: "变价金额" }
          ]
        : title === "加料选择"
        ? [
            { type: "selection", width: 80 },
            { prop: "name", label: "加料名称", align: "left" },
            { prop: "price", label: "加料价格" }
          ]
        : title === "菜品选择"
        ? [
            { type: "selection", width: 80 },
            { prop: "name", label: "菜品名称", align: "left" },
            { prop: "foodTypeName", label: "分类", width: 120 },
            { prop: "foodSpecName", label: "规格", width: 100 },
            { prop: "posPrice", label: "菜品价格", width: 100 }
          ]
        : undefined,
    idName:
      title === "做法选择"
        ? "taskTypeId"
        : title === "加料选择"
        ? "feedTypeId"
        : title === "菜品选择"
        ? "foodCategoryId"
        : undefined,
    treeApi:
      title === "做法选择"
        ? getFoodtaskCategory
        : title === "加料选择"
        ? getFoodFeedCategory
        : title === "菜品选择"
        ? getFoodCategoryList
        : undefined,
    api:
      title === "做法选择"
        ? getFoodtaskList
        : title === "加料选择"
        ? getFoodFeedList
        : title === "菜品选择"
        ? getGoodsSingleItem
        : undefined
  };
  selectTableRef.value?.acceptParams(params);
};

const onAddSpecItem = () => {
  goodsForm.speclist.push({
    isDefault: false,
    specName: `规格${goodsForm.speclist.length + 1}`,
    id: 0,
    corpId: 0,
    storeId: 0,
    foodId: 0,
    code: "",
    onLine: true,
    isShare: true,
    isDelete: true,
    foodShopPriceId: 0,
    posPrice: 0,
    vipPrice: 0,
    purPrice: 0,
    rmoPrice: 0,
    isSelected: true,
    isExclusive: true,
    name: "",
    price: 0
  });
};
const deleteTaskRow = (index: number, name: string) => {
  if (name === "tasklist") {
    goodsForm.tasklist.splice(index, 1);
  } else if (name === "feedlist") {
    goodsForm.feedlist.splice(index, 1);
  }
};
const handleSelectedList = (val: any) => {
  if (val.title === "做法选择") {
    if (val.list.length > 0) {
      let list = val.list.map(im => {
        return {
          taskName: im.name,
          feedPrice: im.feedPrice,
          selectType: 0,
          minQuantity: 0,
          maxQuantity: 0,
          taskPrice: im.price,
          taskId: im.id
        };
      });
      goodsForm.tasklist = replaceArrayItems(list, goodsForm.tasklist, "taskId");
    }
  } else if (val.title === "加料选择") {
    if (val.list.length > 0) {
      let list = val.list.map(im => {
        return {
          feedName: im.name,
          feedPrice: im.price,
          selectType: 0,
          minQuantity: 0,
          maxQuantity: 0,
          feedId: im.id
        };
      });
      goodsForm.feedlist = replaceArrayItems(list, goodsForm.feedlist, "feedId");
    }
  } else if (val.title === "菜品选择") {
    if (val.list.length > 0) {
      let list = val.list.map(im => {
        return {
          quantity: 1,
          foodName: im.name,
          specName: im.foodSpecName,
          foodSpecId: im.foodSpecId,
          setPrice: im.posPrice,
          foodId: im.id
        };
      });
      goodsForm.packlist[val.index].packdetails = replaceArrayItems(list, goodsForm.packlist[val.index].packdetails, "foodId");
    }
  }
};

const categoryDialogRef = ref<InstanceType<typeof CategoryDialog> | null>(null);
const openCategoryDialog = (title: string, row: Partial<Goods.ResGoodsCategoryList> = {}) => {
  const params = {
    title,
    row: { ...row },
    isView: false,
    api: addFoodCategory,
    getTableList: getFCategoryList
  };
  categoryDialogRef.value?.acceptParams(params);
};

const getFCategoryList = () => {
  getFoodCategoryList({ pageNum: 1, pageSize: 9999, listType: goodsForm.isModify ? 0 : 1 }).then(res => {
    foodType.value = transformCategories(res.data.list, "name", "id", true);
  });
};

const onSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      if (isEdit.value) {
        await editFood(goodsForm).then(() => {
          router.push({
            path: "/goods/goods-list",
            query: {
              upList: true
            }
          });
        });
      } else {
        await createFood(goodsForm).then(() => {
          router.push({
            path: "/goods/goods-list",
            query: {
              upList: true
            }
          });
        });
      }
    } catch (error) {
      console.log(error);
    }
  });
};

const addPackGrou = () => {
  goodsForm.packlist.push({
    name: "",
    selectType: 2,
    plateType: 0,
    quantityStar: 1,
    quantityEnd: 1,
    isSelectSame: false,
    isDelete: true,
    packdetails: []
  });
};

const moveUp = (index: number) => {
  let arr = goodsForm.packlist;
  arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]));
};
const moveDown = (index: number) => {
  let arr = goodsForm.packlist;
  arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]));
};
const departmentList = ref([]);
onMounted(async () => {
  const [foodTy, orz, department] = await Promise.all([
    getFoodCategoryList({ pageNum: 1, pageSize: 9999, listType: goodsForm.isModify ? 0 : 1 }),
    getOrganizationList(),
    getDepartMentList({ pageNum: 1, pageSize: 9999 })
  ]);
  foodType.value = transformCategories(foodTy.data.list, "name", "id", true);
  organization.value = orz.data.list;
  departmentList.value = department.data.list;
  useSelectStore()
    .getDic("WarrantyType")
    .then(data => {
      timeUnit.value = data;
    });
  useSelectStore()
    .getDic("FoodPackSelectType")
    .then(data => {
      collocation.value = data;
    });
  useSelectStore()
    .getDic("SalesStatus")
    .then(data => {
      sales.value = data;
    });
  useSelectStore()
    .getDic("MallStatus")
    .then(data => {
      mall.value = data;
    });
  if (route.query.id) {
    isEdit.value = true;
    getFoodDedail({ id: route.query.id }).then(res => {
      Object.keys(goodsForm).forEach(key => {
        if (res.data.hasOwnProperty(key)) {
          goodsForm[key] = res.data[key];
        }
      });
    });
  } else {
    goodsForm.foodTypeId = foodTy.data.list.length > 0 ? foodTy.data.list[0].id : "";
    goodsForm.organizationId = orz.data.list.length > 0 ? orz.data.list[0].id : "";
  }
});

// 监听数据菜品类型
const waresCategory = ref([]);
const onWaresCategoryList = async () => {
  const res = await getWaresCategoryList();
  waresCategory.value = transformCategories(res.data, "name", "id", true);
  console.log(res);
};
watch(
  () => goodsForm.detail.isGoods,
  newValue => {
    if (newValue) {
      onWaresCategoryList();
    } else {
      // 当不是原料时原料id复原为空
      goodsForm.detail.goodsCategoryId = "";
    }
  }
);
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
